// UserController.java
package com.ny.controller;

import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/findNickName")
    public String findNickName(String nickname) {
        User user = userService.findNickname(nickname);
        System.out.println(user);
        return nickname;
    }

    // 添加注册接口
    @PostMapping("/register")
    public String register(@RequestBody User user) {
        // 检查用户是否已存在
        User existingUser = userService.findNickname(user.getNickname());
        if (existingUser != null) {
            return "用户昵称已存在";
        }

        // 执行注册
        boolean result = userService.registerUser(user);
        if (result) {
            return "注册成功";
        } else {
            return "注册失败";
        }

    }
    // 添加登录接口
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session) {
        User user = userService.login(username, password);
        if (user != null) {
            // 将用户信息保存到session中
            session.setAttribute("user", user);
            return "登录成功";
        } else {
            return "用户名或密码错误";
        }
    }

    // 添加登出接口
    @PostMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "登出成功";
    }
    
    // 根据邮箱查询用户接口
    @GetMapping("/findUserByEmail")
    public Result findUserByEmail(String email){
       User user =  userService.findUserByEmail(email);
       if ( user!=null){
           return Result.success(user);
       }
       else {
           return Result.error("该邮箱号不存在");
       }
    }
    
    // 发送验证码接口
    @GetMapping("/sendEmail")
    public Result sendEmail(String toEmail){
        if (toEmail!=null && userService.findUserByEmail(toEmail)!=null){
            userService.sendToEmail(toEmail);
            return Result.success("发送成功");
        }
        return Result.error("发送失败,该邮箱号不存在");
    }
    
    // 验证验证码并修改密码接口
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String code = request.get("code");
        String newPassword = request.get("newPassword");
        
        if (email == null || code == null || newPassword == null) {
            return Result.error("参数不完整");
        }
        
        return userService.verifyCodeAndUpdatePassword(email, code, newPassword);
    }
}